<template>
  <div>
    <UploadExcel :on-success="onSuccess" />
  </div>
</template>

<script>
import { importEmployeeApi } from '@/api/employees'
export default {
  components: {},
  data() {
    return {}
  },
  computed: {
    // 通过type区分是哪里的上传
    type() {
      return this.$route.query.type
    }
  },
  methods: {
    // 时间格式化
    formatDate(numb, format) {
      const time = new Date(numb * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    },
    async onSuccess({ header, results }) {
      // 如果是user的上传就执行下面逻辑
      if (this.type === 'user') {
        const userRelations = {
          '入职日期': 'timeOfEntry',
          '手机号': 'mobile',
          '姓名': 'username',
          '转正日期': 'correctionTime',
          '工号': 'workNumber'
        }
        // 遍历数组对象
        const arr = results.map(ele => {
          const newEle = {} // 声明一个空对象
          // 拿到所有的汉字键
          Object.keys(ele).forEach(key => {
            if (userRelations[key] === 'timeOfEntry' || userRelations[key] === 'correctionTime') {
              newEle[userRelations[key]] = this.formatDate(ele[key], '-')
            } else {
            // 对新对象添加属性
              newEle[userRelations[key]] = ele[key]
            }
          })
          return newEle
        })
        await importEmployeeApi(arr)
        this.$router.back()
      }
    }
  }

}
</script>

<style scoped lang='scss'>

</style>
